package org.bonorsoft.modules.utils;

import com.google.zxing.BarcodeFormat;
import com.google.zxing.EncodeHintType;
import com.google.zxing.MultiFormatWriter;
import com.google.zxing.common.BitMatrix;
import com.google.zxing.qrcode.decoder.ErrorCorrectionLevel;
import org.apache.commons.codec.binary.Base64;

import javax.imageio.ImageIO;
import java.awt.*;
import java.awt.geom.RoundRectangle2D;
import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.HashMap;

public class ZxingUtil {

    public static String createImage(String text, InputStream imgPath) throws  Exception{
        HashMap map = new HashMap();
        //纠错程度，二维码精度（二维码精度越高，扫出来的概率越大）
        map.put(EncodeHintType.ERROR_CORRECTION, ErrorCorrectionLevel.H);
        //字符编码
        map.put(EncodeHintType.CHARACTER_SET,"utf-8");
        map.put(EncodeHintType.MARGIN,1);//边距

        //存储的是二维码的点
        BitMatrix bitMatrix = new MultiFormatWriter().encode(text, BarcodeFormat.QR_CODE, 300, 300, map);
        int width = bitMatrix.getWidth();
        int height = bitMatrix.getHeight();
        BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
        for (int x = 0; x < width; ++x){
            for (int y = 0; y < height; ++y){
                image.setRGB(x, y, bitMatrix.get(x, y) ? 0xFF000000 : 0xFFFFFFFF);
            }
        }
        if (imgPath == null){
            return imageToString(image);
        }
        image = insertLogo(image, imgPath);
        return imageToString(image);
    }

    private static BufferedImage insertLogo(BufferedImage image, InputStream imgPath) throws Exception {
        Image logo = ImageIO.read(imgPath);
        int width = logo.getWidth(null);
        int height = logo.getHeight(null);
        if (width > 100) width = 100;
        if (height > 100) height = 100;

        Image logoInstance = logo.getScaledInstance(width, height, Image.SCALE_SMOOTH);
        BufferedImage bufferedImage = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
        Graphics g = bufferedImage.getGraphics();
        g.drawImage(logoInstance, 0, 0, null);
        g.dispose();

        Graphics2D graphics = image.createGraphics();
        int x = (300 - width)/2;
        int y = (300 - height)/2;
        graphics.drawImage(logoInstance, x, y, null);
        Shape shape = new RoundRectangle2D.Float(x, y, width, height, 6, 6);//圆角矩形
        graphics.setStroke(new BasicStroke(3f));//设置画笔的粗细
        graphics.draw(shape);
        graphics.dispose();
        return image;
    }


    /**
     * image对象转换成base64
     */
    public static  String imageToString(BufferedImage image) throws IOException {
        //字节数组流
        ByteArrayOutputStream os = new ByteArrayOutputStream();
        //操作图片工具类
        ImageIO.write(image, "png", os);
        return Base64.encodeBase64String(os.toByteArray());
    }
}
